package com.example.assignment4;

import com.alibaba.fastjson.JSON;
import com.example.assignment4.exception.R;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URI;
import java.net.URISyntaxException;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class assinmentTest1 {

    @Autowired
    private com.example.assignment4.service.commodityService commodityService;

    @Autowired
    private TestRestTemplate restTemplate;

    @LocalServerPort
    int randomServerPort;

    //尝试用spring boot自带的web测试进行测试，接口是否可以访问并得到response
    @Test
    void addTest() throws URISyntaxException {
        final String baseUrl = "http://localhost:"+randomServerPort+"/commodity";
        URI uri = new URI(baseUrl);
        commodity commodity = new commodity(1l, "book", 1);

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<com.example.assignment4.commodity> request = new HttpEntity<>(commodity, headers);

        ResponseEntity<String> responseEntity=restTemplate.postForEntity(uri, request, String.class);
        R r=JSON.parseObject(responseEntity.getBody(),R.class);

        //判断接口是否接收数据并成功添加
        Assert.assertEquals(200,responseEntity.getStatusCodeValue());
        Assert.assertEquals(1,(long)r.getCode());
        Assert.assertEquals("添加成功",r.getData());

    }

    //
    @Test
    void getByIdTest() throws URISyntaxException {
        commodity commodity=new commodity(1l,"book",20);
        commodityService.add(commodity);
        Assert.assertEquals(commodityService.getById(1l),commodity);
    }

    @Test
    void updateByIdTest(){
        commodity commodity=new commodity(1l,"book",20);
        commodityService.add(commodity);
        commodity.setPrice(30);
        commodityService.updateById(commodity);
        Assert.assertEquals(commodityService.getById(1l).getPrice(),commodity.getPrice(),0);
    }

    @Test
    void deleteByIdTest(){
        commodity commodity=new commodity(1l,"book",20);
        commodityService.add(commodity);
        commodityService.deleteById(1l);
        Assert.assertEquals(commodityService.getById(1l),null);
    }

}
